import os
from datetime import datetime
from textual import on, work
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, ListView, ListItem, Static, Label
from textual.containers import Horizontal, Vertical, VerticalScroll
from rich.console import Console
from rich.table import Table
import subprocess
from repoutil import RepoUtil, Manifest, Project

class ProjectList(ListView):
    '''项目列表'''

    class ProjectItem(ListItem):
        '''项目列表项'''
        def __init__(self, project: Project):
            super().__init__(Static(project.name))
            self.project = project

    def __init__(self, manifest: Manifest):
        super().__init__()
        self.projects = manifest.project

    def on_mount(self) -> None:
        # for project in self.projects:
        #     self.append(ProjectList.ProjectItem(project))
        self.extend([ProjectList.ProjectItem(project) for project in self.projects])

class CommitPreview(Static):
    '''提交信息预览'''
    def __init__(self, commit_message=""):
        super().__init__(commit_message)

class RepoApp(App):
    

    CSS_PATH = "app.tcss"

    BINDINGS = [("q", "quit", "Quit")]

    def __init__(self):
        super().__init__()
        self.manifest = RepoUtil.Manifest()
        self.selected_commit = ""

    def compose(self) -> ComposeResult:
        yield Header()
        yield Horizontal(
            ProjectList(manifest=self.manifest),
            VerticalScroll(Static(id="commit_preview")),
            id="main_area"
        )
        yield Footer()

    def on_mount(self) -> None:
        # self.set_interval(10, self.update_projects)
        self.query_one(ProjectList).focus()

    def update_projects(self):
        self.projects = self.get_latest_commits()
        self.query_one("#project_list").clear()
        for project in self.projects:
            self.query_one("#project_list").append(ListItem(project['name'], sub_title=project['last_commit']))

    def get_latest_commits(self):
        repo_path = os.getcwd()
        projects = []
        for root, dirs, files in os.walk(repo_path):
            if '.git' in dirs:
                project_path = root
                project_name = os.path.basename(project_path)
                commit_info = self.get_latest_commit(project_path)
                projects.append({'name': project_name, 'last_commit': commit_info})
        return sorted(projects, key=lambda x: x['last_commit'], reverse=True)

    def get_latest_commit(self, project: Project):
        # try:
            # result = subprocess.run(['git', '-C', project_path, 'log', '-1', '--pretty=format:%h %ad %s'], capture_output=True, text=True)
            # commit_info = result.stdout.strip()
            # return commit_info if commit_info else "No commits"
        # except Exception as e:
            # return f"Error: {str(e)}"
        try:
            result =subprocess.run(['repo', 'forall', project.path, '-c', 'git', 'log', '-1', '--pretty=format:%h %an %ar'], capture_output=True, text=True)
            commit_info = result.stdout.strip()
            return commit_info if commit_info else "No commits"
        except Exception as e:
            return f"Error: {str(e)}"
        # return

    def get_latest_commit_info(self, project: Project):
        try:
            result =subprocess.run(['repo', 'forall', project.path, '-c', 'git', 'log', '-10'], capture_output=True, text=True)
            commit_info = result.stdout.strip()
            return commit_info if commit_info else "No commits"
        except Exception as e:
            return f"Error: {str(e)}"

    # def on_list_view_selected(self, event: ListView.Selected):
    #     selected_item: ProjectList.ProjectItem = event.item
    #     self.selected_commit = self.get_latest_commit(selected_item.project)
    #     self.query_one("#commit_preview").update(self.selected_commit)
    #     self.sub_title = self.selected_commit


    @work(thread=True)
    def do_project_info(self, project: Project):
        self.selected_commit = self.get_latest_commit(project)
        self.selected_commit_info = self.get_latest_commit_info(project)
        # self.call_from_thread(self.do_project_info, project)
        self.sub_title = self.selected_commit
        # self.query_one("#commit_preview", Static).update(self.selected_commit_info)

    def on_list_view_highlighted(self, event: ListView.Highlighted):
        selected_item: ProjectList.ProjectItem = event.item
        self.do_project_info(selected_item.project)

        # self.selected_commit = self.get_latest_commit(selected_item.project)
        # self.selected_commit_info = self.get_latest_commit_info(selected_item.project)
        # self.query_one("#commit_preview").update(self.selected_commit)
        # self.sub_title = self.selected_commit
        # self.query_one("#commit_preview", Static).update(self.selected_commit_info)
    
    # def on_project_list_project_selected(self, event: ProjectList.Selected):
    #     # selected_item: ProjectList.ProjectItem = event.item
    #     selected_item: ProjectList.ProjectItem = event
    #     self.selected_commit = self.get_latest_commit(selected_item.project)
    #     self.selected_commit_info = self.get_latest_commit_info(selected_item.project)
    #     self.query_one("#commit_preview").update(self.selected_commit)
    #     self.sub_title = self.selected_commit
    #     self.query_one("#commit_preview").update(self.selected_commit_info)


if __name__ == "__main__":
    app = RepoApp()
    app.run()